package com.tdu.spider.biz.service.same;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.tdu.spider.biz.service.same.vo.UserInfoQuery;
import com.tdu.spider.dao.SameChannelRepository;
import com.tdu.spider.model.SameChannelDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SameChannelService {

    @Autowired
    private SameApiService sameApiService;

    @Autowired
    private SameChannelRepository sameChannelRepository;

    private static LoadingCache<Long, SameChannelDO> sameChannelDOLoadingCache = null;

    @PostConstruct
    public void init() {
        sameChannelDOLoadingCache = CacheBuilder.newBuilder().expireAfterAccess(12, TimeUnit.HOURS).build(new CacheLoader<Long, SameChannelDO>() {
            @Override
            public SameChannelDO load(Long key) throws Exception {
                return sameChannelRepository.findById((key)).get();
            }
        });
    }

    public boolean remove(Long channelId) {
        sameChannelRepository.deleteById(channelId);
        return true;
    }


    public SameChannelDO get(Long id) {
        try {
            return sameChannelDOLoadingCache.get(id);
        } catch (Exception e) {
            return null;
        }
    }

    public SameChannelDO saveChannel(Long channelId)throws Exception {
        SameChannelDO sameChannelDO = this.get(channelId);
        if(sameChannelDO!=null){
            return sameChannelDO;
        }
        UserInfoQuery query = new UserInfoQuery();
        query.setChannelId(channelId);
        query.setUserId(15752075L);
        SameChannelDO channelDO = sameApiService.queryChannelDetail(query);
        if(channelDO!=null){
            this.save(channelDO);
        }
        return channelDO;
    }


    public void save(SameChannelDO sameChannelDO){
        sameChannelRepository.save(sameChannelDO);
    }

    public List<SameChannelDO> getAll() {
        Sort sort=Sort.by(new Sort.Order(Sort.Direction.DESC,"times"));
        List<SameChannelDO> sameChannelRepositoryAll = sameChannelRepository.findAll(sort);
        for (SameChannelDO sameChannelDO : sameChannelRepositoryAll) {
            sameChannelDOLoadingCache.put(sameChannelDO.getId(),sameChannelDO);
        }
        return sameChannelRepositoryAll;
    }

    public void put(SameChannelDO sameChannelDO) {
        sameChannelRepository.save(sameChannelDO);
    }
}
